layui.use(['form', 'table', 'element'], function () {
    var $ = layui.jquery;
    var form = layui.form;
    var table = layui.table;
    var element = layui.element;

    /**
     * gprs流量使用量查询条件
     */
    var SimGprs = {
        tableId: "simGprsTable",    //表格id
        condition: {
            dateType: "",
            queryDate: "",
            queryType: "",
            msisdn: "",
            iccid: "",
            imsi: ""
        }
    };

    /**
     * 短信流量使用量查询条件
     */
    var SimSms = {
        tableId: "simSmsTable",    //表格id
        condition: {
            dateType: "",
            queryDate: "",
            queryType: "",
            msisdn: "",
            iccid: "",
            imsi: ""
        }
    };

    /**
     * 语音流量使用量查询条件
     */
    var SimVoice = {
        tableId: "simVoiceTable",    //表格id
        condition: {
            dateType: "",
            queryDate: "",
            queryType: "",
            msisdn: "",
            iccid: "",
            imsi: ""
        }
    };

    /**
     * 初始化gprs表格的列
     */
    SimGprs.initColumn = function () {
        return [[
            {field: 'queryDate', align: "center", title: '时间'},
            {field: 'msisdn', align: "center", title: 'MSISDN'},
            {field: 'iccid', align: "center", title: 'ICCID'},
            {field: 'imsi', align: "center", title: 'IMSI'},
            {field: 'apnName', align: "center", title: 'APN'},
            {field: 'apnDataAmount', align: "center", title: '使用量（KB）'},
            {field: 'dataAmount', align: "center", title: '总量（KB）'}
        ]];
    };

    /**
     * 初始化短信表格的列
     */
    SimSms.initColumn = function () {
        return [[
            {field: 'queryDate', align: "center", title: '时间'},
            {field: 'msisdn', align: "center", title: 'MSISDN'},
            {field: 'iccid', align: "center", title: 'ICCID'},
            {field: 'imsi', align: "center", title: 'IMSI'},
            {field: 'sms', align: "center", title: '使用量（条）'}
        ]];
    };

    /**
     * 初始化语音表格的列
     */
    SimVoice.initColumn = function () {
        return [[
            {field: 'queryDate', align: "center", title: '时间'},
            {field: 'msisdn', align: "center", title: 'MSISDN'},
            {field: 'iccid', align: "center", title: 'ICCID'},
            {field: 'imsi', align: "center", title: 'IMSI'},
            {field: 'voice', align: "center", title: '使用量（分钟）'}
        ]];
    };

    /**
     * 选项卡点击事件
     *
     * 切换选项卡，加载对应的数据表
     */
    element.on('tab(demo)', function (data) {
        index = data.index;
        if (data.index == "0") {
            simGprsRender();
        } else if (data.index == "1") {
            simSmsRender();
        } else if (data.index == "2") {
            simVoiceRender();
        }
    });

    // 渲染gprs表格
    function simGprsRender() {
        table.render({
            elem: '#' + SimGprs.tableId,
            defaultToolbar: [],
            url: Feng.ctxPath + '/history_usage/list',
            height: "full-98",
            cellMinWidth: 100,
            cols: SimGprs.initColumn(),
            done : function(res, curr, count) {
                merge(res);
            }
        });
    }

    // 渲染短信表格
    function simSmsRender() {
        table.render({
            elem: '#' + SimSms.tableId,
            defaultToolbar: [],
            url: Feng.ctxPath + '/history_usage/list',
            height: "full-98",
            cellMinWidth: 100,
            cols: SimSms.initColumn()
        });
    }

    // 渲染语音表格
    function simVoiceRender() {
        table.render({
            elem: '#' + SimVoice.tableId,
            defaultToolbar: [],
            url: Feng.ctxPath + '/history_usage/list',
            height: "full-98",
            cellMinWidth: 100,
            cols: SimVoice.initColumn()
        });
    }

    /**
     * 加载表格后，合并最后一列
     * @param res
     * @param curr
     * @param count
     */
    function merge(res, curr, count) {
        var data = res.data;
        var mergeIndex = 0;//定位需要添加合并属性的行数
        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
        var columsName = ['dataAmount'];//需要合并的列名称
        var columsIndex = [6];//需要合并的列索引值

        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
            var trArr = $(".layui-table-body>.layui-table").find("tr");//所有行
            for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列

                if (data[i][columsName[k]] === data[i-1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                    mark += 1;
                    tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                        $(this).attr("rowspan", mark);
                    });
                    tdCurArr.each(function () {//当前行隐藏
                        $(this).css("display", "none");
                    });
                }else {
                    mergeIndex = i;
                    mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                }
            }
            mergeIndex = 0;
            mark = 1;
        }
    }

    /**
     * 初始化日期下拉列表框
     * 从本月开始的前6个月
     */
    function searchSixMonths(){
        $('#queryDate').html('');
        var curr = new Date();
        for (var i = 0; i < 6; i ++) {
            var yearVal = curr.getFullYear();
            var monthVal = curr.getMonth() + 1;
            if (monthVal < 10) {
                monthVal = "0" + monthVal;
            }
            var dateStr = yearVal + "" + monthVal;
            $('#queryDate').append(new Option(dateStr, dateStr));
            curr.setMonth(curr.getMonth()-1);
        }
        form.render("select");
    };

    /**
     * 下拉列表框的级联，选择日期类型下拉框初始化日期下拉列表框
     */
    form.on('select(dateType)', function(data) {
        if (data.value == "0") {
            searchSevenDays();
        } else if (data.value == "1") {
            searchSixMonths();
        }
    });

    /**
     * 初始化日期下拉列表框
     *
     * 从昨天开始的前七天
     */
    function searchSevenDays(){
        $('#queryDate').html('');
        var curr = new Date();
        for (var i = 0; i < 7; i ++) {
            curr.setDate(curr.getDate() - 1);
            var yearVal = curr.getFullYear();
            var monthVal = curr.getMonth() + 1;
            if (monthVal < 10) {
                monthVal = "0" + monthVal;
            }
            var dayVal = curr.getDate();
            if (dayVal < 10) {
                dayVal = "0" + dayVal;
            }
            var dateStr = yearVal + "" + monthVal + "" + dayVal;
            $('#queryDate').append(new Option(dateStr, dateStr));
        }
        form.render("select");
    };
    searchSevenDays();
    simGprsRender();

    var index = "0";

    /**
     * 点击查询按钮
     * @param tabIndex 当前选项卡的索引
     */
    function search(tabIndex) {
        var queryData = {};
        queryData['dateType'] = $("#dateType").val()
        queryData['queryDate'] = $("#queryDate").val();
        queryData['queryType'] = tabIndex;
        var msisdnVal = $("#msisdn").val();
        var iccidVal = $("#iccid").val();
        var imsiVal = $("#imsi").val();
        var count = 0;
        if ('' != msisdnVal) {
            count++;
        }
        if ('' != iccidVal) {
            count++;
        }
        if ('' != imsiVal) {
            count++;
        }
        if (count == 0 || count > 1) {
            Feng.error("MSISDN、ICCID、IMSI必须有且只有一项！");
            return;
        }
        queryData['msisdn'] = msisdnVal;
        queryData['iccid'] = iccidVal;
        queryData['imsi'] = imsiVal;
        if (tabIndex == "0") {
            table.reload(SimGprs.tableId, {
                where: queryData
            });
        } else if (tabIndex == "1") {
            table.reload(SimSms.tableId, {
                where: queryData
            });
        } else if (tabIndex == "2") {
            table.reload(SimVoice.tableId, {
                where: queryData
            });
        }
    }

    /**
     * 为按钮添加点击事件
     */
    $(document).on('click',"#btnSearch",function(){
        search(index);
    });

});